import utils from "../../utils/util";
import WxValidate from "../../utils/WxValidate";
const CHAT_PAGE_SIZE = 30; //聊天列表每次请求的条数
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    isShow: {
      type: Boolean,
      value: false,
    },
  },

  lifetimes: {
    attached: function () {
      this._page = 1;
      this._provinceArr = [];
      this._cityArr = [];
      this._regionArr = [];

      this._provincesName = [];
      this._citysName = [];
      this._regionsName = [];

      this._currCityArr = [];
      this._currRegionArr = [];
      this.getAreaAddrData();
    },
    detached: function () {
      // 在组件实例被从页面节点树移除时执行
      console.log("tank-detached");
    },
  },

  /**
   * 组件的初始数据
   */
  data: {
    isShowForm: false,
    formStatus: 1, // 1编辑  添加
    addressList: [],
    areaAddrData: [], //所有城市列表
    // isShowAreaList: false,
    loadStatus: "",
    addrPickerArray: [],
    addrPickerIndex: [0, 0, 0],

    formTitle: "编辑收货地址",

    addrStatus: 2, //是否设置为默认的收获地址 1 是 2否
    addrId: "",
    addrName: "",
    addrMobile: "",
    addrAddress: "",
  },

  /**
   * 组件的方法列表
   */
  methods: {
    chooseAddr(e) {
      let item = e.currentTarget.dataset.item;
      this.setData({
        isShow: false,
      });
      this.triggerEvent("chooseAddr", item);
    },
    //编辑地址
    openEditForm(e) {
      console.log(e.currentTarget.dataset.item);
      let data = e.currentTarget.dataset.item;
      //设置省份的索引
      let currProviceItem = this._provinceArr.filter((item) => item.value == data.provinceId)[0];
      let currCityChild = this._getCurrAddrChild(this._cityArr, currProviceItem.value);
      let cityIndex = currCityChild.lists.findIndex((item) => item.value * 1 == data.cityId);
      let currRegionChild = this._getCurrAddrChild(this._regionArr, currCityChild.lists[cityIndex].value);
      console.log("openAddForm", currProviceItem, currCityChild, currRegionChild, cityIndex);
      this._initValidate();
      this._currCityArr = currCityChild.lists;
      this._currRegionArr = currRegionChild.lists;
      this.data.addrPickerArray[1] = currCityChild.names;
      this.data.addrPickerArray[2] = currRegionChild.names;
      this.data.addrPickerIndex[0] = this._provinceArr.findIndex((item) => item.value == data.provinceId);
      this.data.addrPickerIndex[1] = this._currCityArr.findIndex((item) => item.value == data.cityId);
      this.data.addrPickerIndex[2] = this._currRegionArr.findIndex((item) => item.value == data.areaId);
      this.setData({
        formTitle: "编辑收货地址",
        addrId: data.addrId,
        addrName: data.name,
        addrMobile: data.mobile,
        addrAddress: data.address,
        addrStatus: data.status,
        addrPickerIndex: this.data.addrPickerIndex,
        addrPickerArray: this.data.addrPickerArray,
        isShowForm: true,
      });
    },
    openAddForm() {
      let currProviceItem = this._provinceArr[0];
      let currCityChild = this._getCurrAddrChild(this._cityArr, currProviceItem.value);
      let currRegionChild = this._getCurrAddrChild(this._regionArr, currCityChild.lists[0].value);
      this._initValidate();
      this._currCityArr = currCityChild.lists;
      this._currRegionArr = currRegionChild.lists;
      this.data.addrPickerArray[1] = currCityChild.names;
      this.data.addrPickerArray[2] = currRegionChild.names;
      this.setData({
        formTitle: "添加收货地址",
        addrPickerArray: this.data.addrPickerArray,
        addrPickerIndex: [0, 0, 0],
        addrId: "",
        addrName: "",
        addrMobile: "",
        addrAddress: "",
        formStatus: 2,
        isShowForm: true,
      });
      this._initValidate();
    },
    onAddrDel(e) {
      let data = e.currentTarget.dataset.item;
      wx.showModal({
        title: "提示",
        content: "确定要删除该地址吗？",
        success: (res) => {
          if (res.confirm) {
            utils
              .post("address/delete", {
                addrId: data.addrId,
              })
              .then(() => {
                let addrList = this.data.addressList.filter((item) => item.addrId != data.addrId);
                this.setData({
                  addressList: addrList,
                });
                wx.showToast({
                  title: "删除成功",
                });
                this.triggerEvent("delAddr", data.addrId);
              });
          }
        },
      });
    },
    switchDefaultAddrChange(e) {
      console.log(e);
      this.setData({
        addrStatus: e.detail.value ? 1 : 2,
      });
    },
    //设置默认地址
    setAddrToDefault(e) {
      console.log(e);
      let data = e.currentTarget.dataset.item;
      if (data.status == 1) return;
      utils
        .post("address/setDefault", {
          addrId: data.addrId,
        })
        .then(() => {
          this.data.addressList.forEach((item) => {
            if (item.addrId == data.addrId) {
              console.log(item);
              item.status = 1;
            } else {
              item.status = 2;
            }
          });
          this.setData({
            addressList: this.data.addressList,
          });
          wx.showToast({
            title: "设置成功",
            icon: "none",
          });
        });
    },

    addressListOpen() {
      this._page = 1;
      this.setData({
        addressList: [],
      });
      this.getAddrList();
    },

    // openAreaList() {
    //   this.setData({
    //     isShowAreaList: true
    //   })
    // },
    getAddrList() {
      utils
        .get("address", {
          page: this._page,
        })
        .then((res) => {
          console.log("res", res, res.address.data);
          if (!res.address.data.length) {
            this.setData({
              loadStatus: "none",
            });
          }
          let addressList = this.data.addressList.concat(res.address.data);
          this.setData({
            addressList: addressList,
          });
        });
    },

    getAreaAddrData() {
      utils.get("common/getAreaListForAgent").then((res) => {
        this.setData({
          areaAddrData: res.data,
        });
        res.data.forEach((item) => {
          if (item.level == 1) {
            this._provinceArr.push(item);
            this._provincesName.push(item.name);
          } else if (item.level == 2) {
            this._cityArr.push(item);
            this._citysName.push(item.name);
          } else if (item.level == 3) {
            this._regionArr.push(item);
            this._regionsName.push(item.name);
          }
        });
        let cityChild = this._getCurrAddrChild(this._cityArr, this._provinceArr[0].value);
        let regionChid = this._getCurrAddrChild(this._regionArr, cityChild.lists[0].value);
        this._currCityArr = cityChild.lists;
        this._currRegionArr = regionChid.lists;
        this.setData({
          addrPickerArray: [this._provincesName, cityChild.names, regionChid.names],
        });
        // console.log("address",this._provinceArr,this._provincesName, this._cityArr, this._citysName, this._regionArr,this._regionsName)
      });
    },

    bindAddrPickerConfirm(e) {
      console.log("picker发送选择改变，携带值为", e.detail.value);
      // let currCityChild = this._getCurrAddrChild(this._cityArr, this._provinceArr[this._addrPickerIndexOld[0]].value);
      // let currRegionChild = this._getCurrAddrChild(this._regionArr, currCityChild.lists[0].value);
      // console.log(this._provinceArr)
      // let addrPickerArray = this.data.addrPickerArray;
      // let addrPickerIndex = this.data.addrPickerIndex;
      // let currProviceItem = this._provinceArr[e.detail.value[0]];
      // let currCityChild = this._getCurrAddrChild(this._cityArr, currProviceItem.value);
      // if(currCityChild.names[e.detail.value[1]] !=data.addrPickerArray[1]){

      // }

      // console.log(currProviceItem,currCityChild)
      this.setData({
        addrPickerIndex: e.detail.value,
      });
    },
    bindAddrPickerCancel() {
      console.log("bindAddrPickerCancel");
      let currCityChild = this._getCurrAddrChild(this._cityArr, this._provinceArr[this._addrPickerIndexOld[0]].value);
      let currRegionChild = this._getCurrAddrChild(this._regionArr, currCityChild.lists[this._addrPickerIndexOld[1]].value);
      this.data.addrPickerArray[1] = currCityChild.names;
      this.data.addrPickerArray[2] = currRegionChild.names;

      this._currCityArr = currCityChild.lists;
      this._currRegion = currRegionChild.lists;
      this.setData({
        addrPickerArray: this.data.addrPickerArray,
        addrPickerIndex: this._addrPickerIndexOld,
      });
    },
    bindAddrPickerColumnChange(e) {
      this._addrPickerIndexOld = [...this.data.addrPickerIndex];
      console.log("修改的列为", e.detail.column, "，值为", e.detail.value, this._addrPickerIndexOld);
      let data = {
        addrPickerArray: this.data.addrPickerArray,
        addrPickerIndex: this.data.addrPickerIndex,
      };
      let currCityChild = {},
        currRegionChild = {};
      data.addrPickerIndex[e.detail.column] = e.detail.value;
      switch (e.detail.column) {
        case 0:
          currCityChild = this._getCurrAddrChild(this._cityArr, this._provinceArr[e.detail.value].value);
          currRegionChild = this._getCurrAddrChild(this._regionArr, currCityChild.lists[0].value);
          this._currCityArr = currCityChild.lists;
          this._currRegionArr = currRegionChild.lists;
          data.addrPickerArray[1] = currCityChild.names;
          data.addrPickerArray[2] = currRegionChild.names;
          data.addrPickerIndex[1] = 0;
          data.addrPickerIndex[2] = 0;
          break;
        case 1:
          currRegionChild = this._getCurrAddrChild(this._regionArr, this._currCityArr[e.detail.value].value);
          this._currRegionArr = currRegionChild.lists;
          data.addrPickerArray[2] = currRegionChild.names;
          data.addrPickerIndex[2] = 0;
          break;
      }
      this.setData(data);
    },

    _getCurrAddrChild(list, pid) {
      let res = {
        lists: [],
        names: [],
      };
      list.forEach((item) => {
        if (item.parent == pid) {
          res.lists.push(item);
          res.names.push(item.name);
        }
      });
      console.log("_getCurrAddrChild", res);
      return res;
    },

    formSubmit(e) {
      console.log(this._currCityArr, this._currRegionArr);
      let params = e.detail.value;
      params.provinceId = this._provinceArr[params.provinceId * 1].value;
      params.cityId = this._currCityArr[params.cityId * 1].value;
      params.areaId = this._currRegionArr[params.areaId * 1].value;
      console.log(params);
      if (!this.WxValidate.checkForm(params)) {
        const error = this.WxValidate.errorList[0];
        wx.showToast({
          title: error.msg,
          icon: "none",
        });
      } else {
        utils.post("address/save", params).then((res) => {
          this._page = 1;
          this.setData({
            addressList: [],
            isShowForm: false,
          });
          this.getAddrList();
        });
      }
    },

    _initValidate() {
      let rules = {
        name: {
          required: true,
        },
        mobile: {
          required: true,
          tel: true,
        },
        provinceId: {
          required: true,
        },
        cityId: {
          required: true,
        },
        areaId: {
          required: true,
        },
        address: {
          required: true,
        },
      };
      let messages = {
        name: {
          required: "请输入收件人",
        },
        mobile: {
          required: "请输入手机号码",
          tel: "请输入正确手机号码",
        },
        address: {
          required: "请填写详细地址",
        },
      };
      this.WxValidate = new WxValidate(rules, messages);
    },
  },
});
